from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.exceptions import AuthenticationFailed
from seckill_auth.models import CustomUser
from utils.redis_utils import RedisHelper


# class CookieJWTAuthentication(JWTAuthentication):
#     def authenticate(self, request):
#         if 'login' in request.path:
#             return None
#         # 优先从请求头中获取 Token
#         header = self.get_header(request)
#         if header:
#             return super().authenticate(request)
#
#         # 如果请求头中没有 Token，则尝试从 Cookie 中获取
#         token = request.COOKIES.get('accessToken')
#         if token:
#             try:
#                 validated_token = self.get_validated_token(token)
#                 user = self.get_user(validated_token)
#                 return user, validated_token
#             except Exception as e:
#                 raise AuthenticationFailed("无效的 Token")
#
#         return None


class CustomJWTAuthentication(JWTAuthentication):
    def authenticate(self, request):
        # 调用父类方法验证 Token 并提取用户 ID
        header = self.get_header(request)
        if header is None:
            return None

        raw_token = self.get_raw_token(header)
        if raw_token is None:
            return None

        validated_token = self.get_validated_token(raw_token)

        # 从 Redis 获取用户信息
        redis = RedisHelper()
        user_data = redis.get_cache(str(validated_token))

        if not user_data:
            raise AuthenticationFailed("User not found in cache")

        # 创建一个虚拟的用户对象
        user = CustomUser(
            id=user_data["id"],
            mobile=user_data["mobile"],
        )
        return user, validated_token